package com.itcncp.ucenter.rpc.service.impl;

import com.itcncp.common.annotation.BaseService;
import com.itcncp.common.base.BaseServiceImpl;
import com.itcncp.common.model.OrderCodeType;
import com.itcncp.common.pingplusplus.PingppUtil;
import com.itcncp.common.pingplusplus.model.Charge;
import com.itcncp.common.rongCloud.models.TxtMessage;
import com.itcncp.common.util.*;
import com.itcncp.ucenter.common.ApiConstant;
import com.itcncp.ucenter.common.ApiResult;
import com.itcncp.ucenter.common.ApiResultConstant;
import com.itcncp.ucenter.dao.mapper.UserAccountInfoMapper;
import com.itcncp.ucenter.dao.mapper.UserCustomerInfoMapper;
import com.itcncp.ucenter.dao.mapper.UserRechangeOpJnlMapper;
import com.itcncp.ucenter.dao.model.UserAccountInfo;
import com.itcncp.ucenter.dao.model.UserCustomerInfo;
import com.itcncp.ucenter.dao.model.UserRechangeOpJnl;
import com.itcncp.ucenter.dao.model.UserRechangeOpJnlExample;
import com.itcncp.ucenter.rpc.api.UserRechangeOpJnlService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;

/**
* UserRechangeOpJnlService实现
* Created by itcncp on 2018/1/12.
*/
@Service
@Transactional
@BaseService
public class UserRechangeOpJnlServiceImpl extends BaseServiceImpl<UserRechangeOpJnlMapper, UserRechangeOpJnl, UserRechangeOpJnlExample>
        implements UserRechangeOpJnlService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserRechangeOpJnlServiceImpl.class);

    @Autowired
    UserRechangeOpJnlMapper userRechangeOpJnlDao;

    @Autowired
    UserAccountInfoMapper userAccountInfoDao;

    @Autowired
    UserCustomerInfoMapper userCustomerInfoDao;


    /**
     * 创建充值订单
     * @param userId
     * @param amount
     * @param channel
     * @return
     */
    @Override
    public Object pingppRechargeAmount(Long userId, BigDecimal amount, String channel) {

        // 创建充值订单
        UserRechangeOpJnl userRechangeOpJnl = new UserRechangeOpJnl();

        //充值订单号
        userRechangeOpJnl.setRechargeNo( OrderUtils.createOrderId( OrderCodeType.RECHARGE_NO ) );

        LOGGER.error("生成订单号："+userRechangeOpJnl.getRechargeNo());

        //用户id
        userRechangeOpJnl.setUserId( userId );
        //充值金额
        userRechangeOpJnl.setRechargeAmount( amount );
        //实收金额
        userRechangeOpJnl.setRechargeActAmount( amount );
        //充值费率
        userRechangeOpJnl.setRechargeFee( new BigDecimal( "0" ) );
        //充值时间
        userRechangeOpJnl.setRechargeTime( new Date(  ) );
        //充值状态  1、失败； 2、成功 初始化默认位失败
        userRechangeOpJnl.setRechargeState( new Byte( "1" ) );
        //第三方订单号
        userRechangeOpJnl.setdOrderNo( "" );
        userRechangeOpJnl.setOldBalance( new BigDecimal( "0" ) );
        userRechangeOpJnl.setNowBalance( new BigDecimal( "0" ) );
        userRechangeOpJnl.setRemark( "" );
        BigDecimal pingppAmount = amount;
        // 支付类型
        //充值方式 1、微信 2、支付宝 3、银联 4、银行卡 5、其他
        if (channel.equals( PingppUtil.alipay)) {
            // 支付宝支付 金额乘以100
            //pingppAmount = amount.multiply(new BigDecimal("100"));
            userRechangeOpJnl.setRechargeWay( new Byte( "2" ) );
            pingppAmount = amount;

        } else if (channel.equals(PingppUtil.wx)) {
            // 微信支付
            // pingppAmount = amount.multiply(new BigDecimal("100"));
            userRechangeOpJnl.setRechargeWay( new Byte( "1" ) );
            pingppAmount = amount;
        }else if (channel.equals(PingppUtil.upacp)) {
            // 银联
            // pingppAmount = amount.multiply(new BigDecimal("100"));
            userRechangeOpJnl.setRechargeWay( new Byte( "3" ) );
            pingppAmount = amount;
        }else{
            return  null;
        }

        HashMap<String,Object> paramCharge = new HashMap<String, Object>();
        paramCharge.put("order_no", userRechangeOpJnl.getRechargeNo());
        paramCharge.put("amount", pingppAmount.toString());
        paramCharge.put("channel", channel);
        paramCharge.put("currency", "cny");
        paramCharge.put("subject", "ITC钱包充值" + amount.multiply(new BigDecimal("0.01")) + "元");
        paramCharge.put("body",
                "ITC钱包充值" + amount.multiply(new BigDecimal("0.01")) + "元 时间：" + DateUtils.dateFormat(userRechangeOpJnl.getRechargeTime(), "yyyy-MM-dd HH:mm:ss"));

        HashMap<String,Object> initialMetadata = new HashMap<String,Object>(  );
        // 充值回调标识
        initialMetadata.put("type", "1" );

        paramCharge.put("metadata", initialMetadata);


        LOGGER.error("PINGXX处理订单："+JsonUtils.toString(paramCharge));

        Charge charge = PingppUtil.pingPay(paramCharge);

        if(charge!=null) {
            //创建保存充值订单
            userRechangeOpJnlDao.insertSelective( userRechangeOpJnl );
        }

        return charge;
    }

    /**
     * 充值成功后处理
     * @param orderNo
     * @param transactionno
     * @param channel
     * @return
     */
    @Override
    public Object pingppRechargeCallBack(Long orderNo,String transactionno,String channel) {

        UserRechangeOpJnl userRechangeOpJnl = userRechangeOpJnlDao.selectByPrimaryKey( orderNo );

        if(null == userRechangeOpJnl){
            return  null;
        }

        // 判断订单是否已支付
        //充值状态： 1、失败； 2、成功
        if (null != userRechangeOpJnl.getRechargeState() && userRechangeOpJnl.getRechargeState() == 2) {
            return userRechangeOpJnl;
        }
        //更改充值状态 充值状态： 1、失败； 2、成功
        userRechangeOpJnl.setRechargeState( new Byte( "2" ) );

        //填充第三方订单号
        userRechangeOpJnl.setdOrderNo( transactionno );

        Long userId = userRechangeOpJnl.getUserId();

        //查询账户资金
        UserAccountInfo userAccountInfo = userAccountInfoDao.selectByPrimaryKey( userId );
        if(null == userAccountInfo){
            return  null;
        }

        //查询用户信息
        UserCustomerInfo userInfo = userCustomerInfoDao.selectByPrimaryKey( userId );
        if(null==userInfo){
            return  null;
        }

        //充值方式 1、微信 2、支付宝 3、银联 4、银行卡 5、其他
        if (channel.equals( PingppUtil.alipay)) {
            // 支付宝
            userRechangeOpJnl.setRechargeWay (new Byte( "2" ));
        } else if (channel.equals(PingppUtil.wx)) {
            // 微信支付
            userRechangeOpJnl.setRechargeWay (new Byte( "1" ));
        }else if (channel.equals(PingppUtil.upacp)) {
            // 银联
            userRechangeOpJnl.setRechargeWay (new Byte( "3" ));
        }else{
            userRechangeOpJnl.setRechargeWay (new Byte( "5" ));
        }

        //充值前账户余额
        userRechangeOpJnl.setOldBalance( userAccountInfo.getAccountBalance() );
        // 充值后的金额
        BigDecimal nowBalance = userAccountInfo.getAccountBalance().add(userRechangeOpJnl.getRechargeActAmount());
        //实收金额
        userRechangeOpJnl.setNowBalance( nowBalance );

        //更新账户资金
        userAccountInfo.setAccountBalance( nowBalance );

        // 如果金额超过5元设置自动扣款 扣款方式 1非自动扣款 2自动扣款（不需要密码）
        if (userAccountInfo.getAccountBalance().intValue() > 500) {
            userInfo.setPayMethod(new Byte( "2" ));
            userInfo.setUpdateTime( new Date(  ) );
            //更新用户信息
            userCustomerInfoDao.updateByPrimaryKeySelective( userInfo );
        }

        //更新充值记录
        userRechangeOpJnlDao.updateByPrimaryKeySelective( userRechangeOpJnl );

        //更新账户资金
        userAccountInfoDao.updateByPrimaryKeySelective( userAccountInfo );

        // 发送支付成功信息用户客户端
        Jpush.notifiAccount(userInfo.getDeviceAppNo(), "ITC充值通知，充值成功，金额：" + userRechangeOpJnl.getRechargeAmount() + "元");

        // 推送透传给客户端
        rongCloud.publishSystemMessage( ApiConstant.RONGCLOUD_USERID, userInfo.getDeviceAppNo(),
                new TxtMessage("支付成功", new ApiResult( ApiResultConstant.APP_NOTIFICATION_RECHARGE,userAccountInfo )), "支付成功", "支付成功");

        return userAccountInfo;
    }

}